#include "QU.h"

void QU_init(PQ* p)
{
    assert(p);
    p->phead=p->ptail=NULL;
    p->size=0;
}

void QU_destroy(PQ *p)
{
    assert(p);
    QE*cur = p->phead;
    while(p->size>0 && cur)
    {
        QE* nex = cur->next;
        free(cur);
        cur = nex;
        p->size--;
    }
    p->phead = NULL;
    p->ptail = NULL;
    return ;
}
void QU_push(PQ* p,QUdata x)
{
    assert(p);
    if(p->phead)
    {
        QE* newnode = (QE*)malloc(sizeof(QE));
        if(!newnode)
        {
            perror("malloc fail:\n");
        }
        p->ptail->next = newnode;
        newnode->next = NULL;
        newnode->x = x;
        p->ptail = newnode;
        p->size++;
    }
    else
    {
        p->ptail = p->phead = (QE*)malloc(sizeof(QE));
        if(!p->phead)
        {
            perror("malloc fail:\n");
        }
        p->phead->x = x;
        p->size++;
    }
}
bool QU_empty(PQ* p)
{
    if(p->phead==NULL)
    {
        return 1;
    }
    return 0;
}
void QU_headpop(PQ* p)
{
    assert(p);
    if(!QU_empty(p))
    {
        QE* cur = p->phead->next;
        free(p->phead);
        p->phead = cur;
        if(cur==NULL)
        {
            p->ptail = NULL;
        }
        p->size--;
    }
    else
    {
        perror("the QUEUE is NULL:\n");
    }
}